var $;
var table;
var form
layui.use(['jquery', 'table', 'layer', 'laydate', 'form'], function () {
    /* */
    $ = layui.jquery;
    table = layui.table;
    form = layui.form;
    var layer = layui.layer;
    var laydate = layui.laydate;

    /*渲染树开始*/
    var zTree;
    var demoIframe;

    var setting = {
        view: {
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true,  //true 、 false 分别表示 使用 、 不使用 简单数据模式
                idKey: "id",   //节点数据中保存唯一标识的属性名称
                pIdKey: "parentId",    //节点数据中保存其父节点唯一标识的属性名称
                rootPId: -1  //用于修正根节点父节点数据，即 pIdKey 指定的属性值
            },
            key: {
                enable: true,
                name: "deptName"  //zTree 节点数据保存节点名称的属性名称  默认值："name"
            }
        },
        check: {
            enable: false,
            nocheckInherit: true   //当父节点设置 nocheck = true 时，设置子节点是否自动继承 nocheck = true
        },
        callback: {
            //onRightClick: onRightClick,
            // beforeRemove: beforeRemove,//点击删除时触发，用来提示用户是否确定删除（可以根据返回值 true|false 确定是否可以删除）
            // beforeEditName: beforeEditName,//点击编辑时触发，用来判断该节点是否能编辑
            //beforeRename: beforeRename,//编辑结束时触发，用来验证输入的数据是否符合要求(也是根据返回值 true|false 确定是否可以编辑完成)
            // beforeDrag: beforeDrag,//用户禁止拖动节点
            onClick: chooseNode,
        }
    };
    $(document).ready(function () {
        $.ajax({
            type: "post",
            dataType: "json",
            url: "/newJurisdiction/getDeptName",
            success: function (data) {
                zTree = $.fn.zTree.init($("#tree"), setting, data.data); //初始化树
                zTree.expandAll(true);   //true 节点全部展开、false节点收缩
            }
        });
        demoIframe = $("#rMenu");
    });
    /*表格渲染开始*/
    var people =table.render({
        elem: "#root",
        url: "/newJurisdiction/getUsers?account=" + '' + "&trueName=" + '' + "&deptName=" + '' + "&registerDate=" + '',
        toolbar: "#toptool",
        page:true,
        limit:5,
        limits: [],
        size: "lg",
        cols:[
            [
                {type: "checkbox", align: "center"},
                {type: "numbers", title: "序号", align: "center"},
                {field: "trueName", title: "用户姓名", align: "center"},
                {
                    field: "acatarUrl", title: "用户头像", align: "center", templet: function (data) {
                        return '<img src=' +"http://"+ data.acatarUrl + ' />';
                    }
                },
                {field: "sex", title: "性别", align: "center"},
                {field: "account", title: "用户账号", align: "center"},
                {field: "deptName", title: "所属部门", align: "center"},
                {
                    field: "enabled", title: "是否启用", align: "center", templet: function (data) {
                        if (data.enabled == 1) {
                            var enabled = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '" checked></a>';
                        } else {
                            var enabled = '<a href="javascript:updateStatus(' + data.userId + ',' + data.status + ',' + data.enabled + ');"><input class="layui-input swi" type="checkbox" name="enable" lay-skin="switch" lay-text="启用|停用" lay-filter="switchTest" value="' + data.enable + '"></a>';
                        }
                        return enabled;
                    }
                },
                {
                    field: "status", title: "账号状态", align: "center", templet: function (data) {
                        if (data.status == 1) {
                            var status = '<p>使用中</p>';
                        }else if (data.status == 2) {
                            var status = '<p>已注销</p>'
                        }else if (data.status == 3) {
                            var status = '<p>冻结</p>'
                        }else if (data.status == 4) {
                            var status = '<p>封停</p>'
                        }
                        return status;
                    }
                },
                {field: "registerDate", title: "注册时间", align: "center"},
                {
                    title: "操作", align: "center", templet: function (data) {
                        return "<div>" +
                            "<a href='javascript:getUser(" + data.userId + ");' style='color: #2F4056;margin-right: 10px'>查看</a>" +
                            "<a href='javascript:grade(" + data.userId + ");' style='color: #2F4056'>权限</a><br/>" +
                            "<a href='javascript:bianji(" + data.userId + ");' style='color: #2F4056; margin-right: 10px'>编辑</a>" +
                            "<a href='javascript:fengting(\"" + data.userId + "\",\"" + data.account + "\",\"" + data.status + "\");' style='color: #2F4056'>封停</a>" +
                            "</div>";
                    }
                }
            ]
        ]
    })

    /*点击树节点展示不同用户*/
    function chooseNode(event, treeId, treeNode) {
        var zTree = $.fn.zTree.getZTreeObj(treeId);
        var nodes = zTree.getSelectedNodes();
        var deptName = nodes[0].deptName;
        if (deptName == "所有部门") {
            people.reload({
                url: "/newJurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + '' + "&registerDate=" + '',
            });
        } else {
            people.reload({
                url: "/newJurisdiction/getJsUser?account=" + '' + "&trueName=" + '' + "&deptName=" + deptName + "&registerDate=" + '',
            });
        }
    }
    /* 更新账号状态 */
    updateStatus = function updateStatus(userId, status, enabled) {
        if (status == 1) {
            var status1 = 4;
        } else {
            var status1 = 1;
        }

        if (enabled == 1) {
            var enabledd = 2;
        } else {
            var enabledd = 1;
        }
        var json = {
            userId: userId,
            status: status1,
            enabled: enabledd,
            type:2,
            remarks:"紧急封停"
        };
        $.ajax({
            type: "post",
            dataType: "json",
            data: json,
            url: "/newJurisdiction/updateStatus",
            success: function (data) {
                location.reload();
            }
        });
    }
})
/*获取用户信息*/
grade = function grade(userId){
    localStorage.setItem("gradeId",userId);
    $.ajax({
        type: "post",
        dataType: "json",
        data: {"id": userId},
        url: "/newJurisdiction/getUserPower",
        success: function (data) {
            editUserPower(data);
        }
    })
}
/*渲染权限操作页面*/
function editUserPower(data){
    var obj;
    layer.open({
        type:2,
        shode:0,
        maxmin:true,
        title:"权限设置",
        content: "/newquan/newquan-user-power.html",
        area:["900px","500px"],
        btn: ["完成"],
        btn1: function(index, layero){
            layer.close(index);
        },
        success:function (layero,index) {
            obj = layero.find('iframe').contents();
            obj.find("#userId").val(data[0].userId);
            obj.find("#trueName").val(data[0].trueName);
            obj.find("#remark").val(data[0].remark);
            for(var i=0;i<data.length;i++){
                if(data[i].authorityId==1){
                    obj.find("#guan").prop("checked",true);
                    obj.find("#guan").siblings("div").addClass("layui-form-onswitch");
                    obj.find("#guan").val("1");
                }else if(data[i].authorityId==2){
                    obj.find("#teacher").prop("checked",true);
                    obj.find("#teacher").siblings("div").addClass("layui-form-onswitch");
                    obj.find("#teacher").val("1");
                }
                else if(data[i].authorityId==3){
                    obj.find("#shop").prop("checked",true);
                    obj.find("#shop").siblings("div").addClass("layui-form-onswitch");
                    obj.find("#shop").val("1");
                }
                else if(data[i].authorityId==4){
                    obj.find("#people").attr("checked","checked");
                    obj.find("#people").siblings("div").addClass("layui-form-onswitch");
                    obj.find("#people").val("1");
                }
            }
            form.render();
        }
    });
};

/* 获取编辑用户信息 */
bianji = function bianji(userId){
    $.ajax({
        type: "post",
        dataType: "json",
        data: {"id": userId},
        url: "/newJurisdiction/getUserById",
        success: function (data) {
            console.log(data);
            editUser(data);
        }
    })
};
/*渲染编辑页面*/
function editUser(data) {
    var obj;
    layer.open({
        type:2,
        shode:0,
        maxmin:true,
        title:"编辑用户信息",
        content:"/jurisdiction/jurisdiction-see-uesr-edit.html",
        area:["1000px","620px"],
        btn:["编辑","取消"],
        yes:function (index) {
            var json={
                acatarUrl:obj.find("#mainImage").val(),
                userId:obj.find("#userId").val(),
                account:obj.find("#account").val(),
                trueName:obj.find("#trueName").val(),
                sex:obj.find("#sex").val(),
                phone:obj.find("#phone").val(),
                birthDate:obj.find("#birthDate").val(),
                deptId:obj.find("#deptId").val(),
                email:obj.find("#email").val(),
                freestyle:obj.find("#freestyle").val()
            };
            $.ajax({
                type:"post",
                dataType:"json",
                data:json,
                url:"/newJurisdiction/updateUser",
                success:function (data) {
                    console.log(data.data);
                    layer.close(index);
                }
            });
            location.reload();
        },
        btn2:function(index){
            layer.close(index);
        },
        success:function (layero,index) {
            obj = layero.find('iframe').contents();
            obj.find("#userId").val(data.data.userId);
            obj.find("#acatarUrl").attr('src',"http://"+data.data.acatarUrl);
            obj.find("#account").val(data.data.account);
            obj.find("#trueName").val(data.data.trueName);
            obj.find("#phone").val(data.data.phone);
            obj.find("#birthDate").val(data.data.birthDate);
            obj.find("#registerDate").val(data.data.registerDate);
            obj.find("#registerIp").val(data.data.registerIp);
            obj.find("#email").val(data.data.email);
            obj.find("#freestyle").val(data.data.freestyle);
            var deptName = '';
            if(data.data.deptId==1){
                deptName="管理部";
            }else if(data.data.deptId==2){
                deptName="人事部";
            }else if(data.data.deptId==3){
                deptName="运营部";
            }else{
                deptName="教师部";
            }
            var sex = "";
            if(data.data.sex=="男"){
                sex="男";
            }else{
                sex="女"
            }
            selectLay(obj,data.data.sex,sex,"#sex");
            selectLay(obj,data.data.deptId,deptName,"#deptId");
        }
    });
};
//下拉框矫正
function selectLay(obj,layValue,value,select) {
    obj.find(select).children().each(function () {
        if ($(this).val() == layValue) {
            var status = 'dd[lay-value=' + layValue + ']';
            obj.find(select).siblings("div.layui-form-select").find('dl').find(status).click();
            $(this).parent().append('<option value="'+layValue+'" selected>' + value + '</option>');
        }
    })
}
/* 查看用户详情 */
getUser = function details(userId) {
    $.ajax({
        type: "post",
        dataType: "json",
        data: {"id": userId},
        url: "/newJurisdiction/getUserById",
        success: function (data) {
            devicesMsg(data);
        }
    })
};
/*查看后弹出赋值*/
function devicesMsg(data) {
    var obj;
    layer.open({
        type: 2,
        shode: 0,
        maxmin: true,
        title: "查看用户信息",
        content: "/newquan/newquan-user-see.html",
        area: ["1000px", "620px"],
        btn: ["关闭"],
        yes: function (index) {
            layer.close(index);
        }, success: function (layero, index) {
            obj = layero.find('iframe').contents();
            obj.find("#acatarUrl").attr('src', "http://"+data.data.acatarUrl);
            obj.find("#account").val(data.data.account);
            obj.find("#trueName").val(data.data.trueName);
            obj.find("#sex").val(data.data.sex);
            obj.find("#phone").val(data.data.phone);
            obj.find("#birthDate").val(data.data.birthDate);
            obj.find("#deptName").val(data.data.deptName);
            obj.find("#registerDate").val(data.data.registerDate);
            obj.find("#registerIp").val(data.data.registerIp);
            obj.find("#email").val(data.data.email);
            obj.find("#freestyle").val(data.data.freestyle);
        }
    });
};
/* 封停账户 */
fengting = function fengting(userId,account,status) {
    if(status==4){
        layer.msg("此账号已被封停");
    }else{
        var obj;
        layer.open({
            type:2,
            shode:0,
            maxmin:true,
            title:"账户封停",
            content:"/jurisdiction/jurisdiction-people-list-shutdown.html",
            area:['500px','370px'],
            btn:['确定','取消'],
            yes:function(index){
                var days = obj.find("#days").val();
                var reason = obj.find("#reason").val();
                var startDate = new Date();
                startDate = getTime(startDate);
                var endDate = new Date();
                endDate = getTimes(endDate,days);
                var status = "4";
                var enabled = "2";
                var type = "3";

                var json = {
                    userId:userId,
                    type:type,
                    reason:reason,
                    startDatee:startDate,
                    endDatee:endDate,
                    days:days,
                    status:status,
                    enabled:enabled
                };
                $.ajax({
                    type:"post",
                    dataType:"json",
                    data:json,
                    url:"/newJurisdiction/addUserClosure",
                    success:function (data) {
                        if(data.data){
                            alert("操作成功");
                        }else{
                            alert("服务器异常");
                        }
                        location.reload();
                    }
                });
            },
            btn2:function(index){
                layer.close(index);
            },
            success:function (layero,index) {
                obj = layero.find('iframe').contents();
                obj.find("#account").val(account);
            }
        })
    }
};

/*获取一个当前时间*/
function getTime(date){
    var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
    var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
    var today = date.getDate(); //获取当前日(1-31)
    var hour = date.getHours(); //获取当前小时数(0-23)
    var minute = date.getMinutes(); //获取当前分钟数(0-59)
    var second = date.getSeconds(); //获取当前秒数(0-59)
    var nowTime;
    nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
    return nowTime;
};
/*获取封停时间*/
function getTimes(date,days){
    var year = date.getFullYear(); //获取完整的年份(4位,1970-????)
    var month = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
    var today = date.getDate(); //获取当前日(1-31)
    var hour = date.getHours(); //获取当前小时数(0-23)
    var minute = date.getMinutes(); //获取当前分钟数(0-59)
    var second = date.getSeconds(); //获取当前秒数(0-59)
    days = parseInt(days);
    today = parseInt(today);
    month = parseInt(month);
    year = parseInt(year);
    if(days=="1"){
        today = today+days;
        if(today>32|today>31){
            if(month=1|3|5|7|8|10|12){
                month+=1;
            }else if(month=4|6|9|11){
                month+=1;
            }else{
                month+=1;
            }
        }
    }else if(days=="30"){
        month = month+1;
        if(month>13){
            year=year+1;
        }
    }else if(days=="365"){
        year=year+1;
    }else{
        year=year+100;
    }
    var nowTime;
    nowTime = year+'-'+fillZero(month)+'-'+fillZero(today)+' '+fillZero(hour)+':'+fillZero(minute)+':'+fillZero(second);
    return nowTime;
};

function fillZero(str){
    var realNum;
    if(str<10){
        realNum	= '0'+str;
    }else{
        realNum	= str;
    }
    return realNum;
};